<?php
declare (strict_types=1);

namespace app\listener;

use app\common\job\TradeEnd;
use app\common\model\Consulting;
use app\common\model\ConsultingMessage;
use app\index\service\MessageSendService;
use ShidianUtil\Utils\CheckUtil;
use think\facade\Queue;

class ConsultingServerStart
{
    /**
     * 付费服务生效 事件监听处理
     * 咨询-更新咨询的活动时间
     * 咨询-增加聊天时长
     * 咨询-发送支付成功消息，发送电话号码消息
     * 订单-设置订单结束延迟任务
     * @return void
     */
    public function handle($params)
    {
        $consulting = $params['consulting'] ?? null;
        $server = $params['server'] ?? null;
        $serverSku = $params['serverSku'] ?? null;
        $trade = $params['trade'] ?? null;

        if (is_null($consulting) || is_null($server)) {
            // TODO 记录错误日志

            return;
        }

        // 服务生效

        $now = time();

        $isChatFreely = $server->isChatFreely;
        $chatFreelyDuration = $server->chatFreelyDuration;
        $isShowCallTel = $server->isShowCallTel;
        $questionsNum = $server->questionsNum;
        $serverName = $server->name;
        if ($serverSku) {
            // $isChatFreely = $serverSku->isChatFreely;
            // $isShowCallTel = $serverSku->isShowCallTel;
            $chatFreelyDuration = $serverSku->chatFreelyDuration;
            $questionsNum = $serverSku->questionsNum;
            $serverName = $serverSku->name;
        }

        // 如果是夜间(0:00 ~8:00)那么延长服务时间为24小时
        if (at_night($now)) {
            $chatFreelyDuration = 24;
        }

        // 订单保存服务生效时间
        if ($trade) {
            $trade->startTime = $now;
            $trade->save();

            // 添加订单完成任务
            if ($isChatFreely == 1) {
                $delay = $chatFreelyDuration * 3600 + 10;
            } else {
                $delay = 86400;
            }
            $job_data = ['id' => $trade->id];
            Queue::later($delay, TradeEnd::class, $job_data);
        }

        // 更新咨询的活动时间
        $lastActiveTime = time() + 24 * 3600;
        if ($isChatFreely == 1) {
            $lastActiveTime = time() + $chatFreelyDuration * 3600 + 24 * 3600;
        }
        $consulting->updateActiveTime($lastActiveTime);

        // ************** 聊天时长和次数 ******************

        // 给对应的咨询添加聊天时长和次数
        $this->handleTimeAndNum($consulting, $now, $isChatFreely, $chatFreelyDuration, $questionsNum);

        // 发送电话号码消息
        $this->sendPhoneMessage($isShowCallTel, $trade, $isChatFreely, $serverName, $chatFreelyDuration, $questionsNum, $consulting);

    }

    /**
     * 增加聊天时长和次数
     * @param Consulting $consulting
     * @param $now
     * @param $isChatFreely
     * @param $chatFreelyDuration
     * @param $questionsNum
     * @return void
     */
    private function handleTimeAndNum(Consulting $consulting, $now, $isChatFreely, $chatFreelyDuration, $questionsNum)
    {

        // 对应的咨询添加聊天时长和次数
        if ($isChatFreely == '1') {
            // 畅聊

            $isChatFreelyEndTime = $consulting->isChatFreelyEndTime;
            if ($isChatFreelyEndTime < $now) {
                $isChatFreelyEndTime = $now;
            }
            $isChatFreelyEndTime += $chatFreelyDuration * 3600;

            $consulting->isChatFreely = '1';
            $consulting->isChatFreelyEndTime = $isChatFreelyEndTime;
            $consulting->questionsNumRemind = 0;
            $consulting->save();

            // 给用户消息
            $content = [
                'templates' => [
                    ['type' => 'text', 'red' => '102', 'text' => '支付成功，当前可用聊天时长',],
                    ['type' => 'text', 'red' => '101', 'text' => humanized_time_length($consulting->isChatFreelyEndTime - $now),],
                    ['type' => 'text', 'red' => '102', 'text' => '畅聊截止时间为：' . date('Y-m-d H:i', $consulting->isChatFreelyEndTime),],
                ],
            ];
            $this->getMessageSendService()->sendSystemMessage($consulting, $consulting->memberId, ConsultingMessage::SYSTEM, $content);

            // 给律师消息
            if (is_id($consulting->lawyerId)) {
                $content = [
                    'templates' => [
                        ['type' => 'text', 'red' => '102', 'text' => '用户支付成功,畅聊截止时间为：' . date('Y-m-d H:i', $consulting->isChatFreelyEndTime),]
                    ],
                ];
                $this->getMessageSendService()->sendSystemMessage($consulting, $consulting->lawyerId, ConsultingMessage::SYSTEM, $content);
            }

        } else {
            //次数

            $consulting->questionsNum += $questionsNum;
            $consulting->questionsNumRemind = 0;
            $consulting->save();

            // 给用户消息
            $content = [
                'templates' => [
                    ['type' => 'text', 'red' => '102', 'text' => '支付成功，当前可用聊天次数为：',],
                    ['type' => 'text', 'red' => '101', 'text' => $consulting->questionsNum . '次',]
                ],
            ];
            $this->getMessageSendService()->sendSystemMessage($consulting, $consulting->memberId, ConsultingMessage::SYSTEM, $content);

            // 给律师消息
            if (is_id($consulting->lawyerId)) {
                $content = [
                    'templates' => [
                        ['type' => 'text', 'red' => '102', 'text' => '用户支付成功,剩余聊天次数为：' . $consulting->questionsNum . '次',]
                    ],
                ];
                $this->getMessageSendService()->sendSystemMessage($consulting, $consulting->lawyerId, ConsultingMessage::SYSTEM, $content);
            }
        }

    }

    /**
     * 发送电话号码消息
     * @param $isShowCallTel
     * @param $trade
     * @param $isChatFreely
     * @param $serverName
     * @param $chatFreelyDuration
     * @param $questionsNum
     * @param $consulting
     * @return void
     */
    private function sendPhoneMessage($isShowCallTel, $trade, $isChatFreely, $serverName, $chatFreelyDuration, $questionsNum, $consulting): void
    {

        if ($isShowCallTel != '1') {
            return;
        }

        $phone = $trade->attach['memberPhone'] ?? '';
        if (!CheckUtil::isPhoneNumber($phone)) {
            // TODO 记录错误
            return;
        }

        // 发电话号码消息
        if ($isChatFreely == 1) {
            $content = [
                'text' => '客户支付成功，客户购买项目：' . $serverName . '，聊天时限：' . humanized_time_length($chatFreelyDuration * 3600),
                'phone' => $phone,
            ];
        } else {
            $content = [
                'text' => '客户支付成功，客户购买项目：' . $serverName . '，聊天次数：' . $questionsNum . '次',
                'phone' => $phone,
            ];
        }
        $this->getMessageSendService()->sendSystemMessage($consulting, 0, ConsultingMessage::PHONE, $content);

        //

        // 给用户消息
        $content = [
            'templates' => [
                ['type' => 'text', 'red' => '102', 'text' => '支付成功，请输入基本案情后，系统推荐专业律师给您来电',]
            ],
        ];
        $this->getMessageSendService()->sendSystemMessage($consulting, $consulting->memberId, ConsultingMessage::SYSTEM, $content);
    }

    private function getMessageSendService(): MessageSendService
    {
        return app(MessageSendService::class);
    }

}
